//
//  HZHttpRequestHandler.m
//  Expert
//
//  Created by 刘华舟 on 15/4/3.
//  Copyright (c) 2015年 BLUEBLACK. All rights reserved.
//

#import "HZHttpRequestHandler.h"
#import "AFNetworking.h"
#import "NSString+Conveniently.h"
#import "NSDictionary+SafetyGet.h"
#import "NSDate+Conveniently.h"


#define HZHttpRequestHandlerRequestFailureErrorMessage @"网络状况不良，请检查网络"
#define HZHttpRequestHandlerHttpFileDataExceptionMessage @"The elements in the files array is not a HZHttpFileData."

// 网络请求的错误信息
#define HTTP_REQUEST_ERROR_MESSAGE(error, operation) NSLog(@"网络请求错误：\n%@\n\n错误信息：\n%@", error, operation.responseString)

@implementation HZHttpRequestHandler

+ (void)GETWithURL:(NSString *)url parameters:(NSDictionary *)parameters showProgressInView:(UIView *)view isHideProgress:(BOOL)isHideProgress success:(void (^)(NSDictionary *))success failure:(void (^)(NSError *))failure{
    
    
    AFHTTPRequestOperationManager *manager = [self requestOperationManager];
    url = [[NSString stringWithFormat:@"%@%@", HZHttpRequestAddressHeader, url] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [manager GET:url parameters:parameters success:^(AFHTTPRequestOperation *operation, NSDictionary *dataDictionary) {
       
        
        if([dataDictionary longLongForKey:@"code"] == HZHttpRequestHandlerResponseCodeSessionInvalid){
            if(failure){
                failure(nil);
            }
        }else{
            if(success){
                success(dataDictionary);
            }
        }
    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        if(failure){
            failure(error);
        }
        HTTP_REQUEST_ERROR_MESSAGE(error, operation);
    }];
}

+ (void)PUTWithURL:(NSString *)url parameters:(NSDictionary *)parameters showProgressInView:(UIView *)view isHideProgress:(BOOL)isHideProgress success:(void (^)(NSDictionary *dataDictionary))success failure:(void (^)(NSError *error))failure{
   
    
    AFHTTPRequestOperationManager *manager = [self requestOperationManager];
    url = [[NSString stringWithFormat:@"%@%@", HZHttpRequestAddressHeader, url] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [manager PUT:url parameters:parameters success:^(AFHTTPRequestOperation *operation, NSDictionary *dataDictionary) {
        
        if([dataDictionary longLongForKey:@"code"] == HZHttpRequestHandlerResponseCodeSessionInvalid){
            if(failure){
                failure(nil);
            }
        }else{
            if(success){
                success(dataDictionary);
            }
        }
    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if(failure){
            failure(error);
        }
        HTTP_REQUEST_ERROR_MESSAGE(error, operation);
    }];
}
+ (void)POSTWithURL:(NSString *)url parameters:(NSDictionary *)parameters showProgressInView:(UIView *)view isHideProgress:(BOOL)isHideProgress success:(void (^)(NSDictionary *))success failure:(void (^)(NSError *))failure{
    
    AFHTTPRequestOperationManager *manager = [self requestOperationManager];
    url = [[NSString stringWithFormat:@"%@%@", HZHttpRequestAddressHeader, url] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, NSDictionary *dataDictionary) {
        
        if([dataDictionary longLongForKey:@"code"] == HZHttpRequestHandlerResponseCodeSessionInvalid){
            if(failure){
                failure(nil);
            }
        }else{
            if(success){
                success(dataDictionary);
            }
        }
    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if(failure){
            failure(error);
        }
        HTTP_REQUEST_ERROR_MESSAGE(error, operation);
    }];
}

+ (void)POSTWithURL:(NSString *)url parameters:(NSDictionary *)parameters datas:(NSArray *)datas showProgressInView:(UIView *)view isHideProgress:(BOOL)isHideProgress success:(void (^)(NSDictionary *))success failure:(void (^)(NSError *))failure{
    for(NSInteger i = 0; i < datas.count; i ++){
        if(![datas[i] isKindOfClass:[HZHttpFileData class]]){
            [NSException raise:HZHttpRequestHandlerHttpFileDataExceptionMessage format:nil];
            return;
        }
    }
    
    AFHTTPRequestOperationManager *manager = [self requestOperationManager];
    url = [[NSString stringWithFormat:@"%@%@", HZHttpRequestAddressHeader, url] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData){
        for(HZHttpFileData *data in datas){
            [formData appendPartWithFileData:data.data name:data.parameterName fileName:data.fileName mimeType:data.mimeType];
        }
    }success:^(AFHTTPRequestOperation *operation, NSDictionary *dataDictionary){
        if([dataDictionary longLongForKey:@"code"] == HZHttpRequestHandlerResponseCodeSessionInvalid){
            if(failure){
                failure(nil);
            }
        }else{
            if(success){
                success(dataDictionary);
            }
        }
    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        if(failure){
            failure(error);
        }
        HTTP_REQUEST_ERROR_MESSAGE(error, operation);
    }];
}

+ (void)cancelAllRequest{
    AFHTTPRequestOperationManager *manager = [self requestOperationManager];
    [manager.operationQueue cancelAllOperations];
}

+ (AFHTTPRequestOperationManager *)requestOperationManager{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer.timeoutInterval = HZHttpRequestTimeoutInterval;
    return manager;
}

@end
